import {
    Card,
    Breadcrumb,
    Form,
    Button,
    Radio,
    Input,
    Upload,
    Space,
    Select,
    message
} from "antd";
import { PlusOutlined } from "@ant-design/icons";
import { Link, useSearchParams } from "react-router-dom";
import "./index.scss";
import ReactQuill from "react-quill";
import "react-quill/dist/quill.snow.css";
import { useEffect, useState } from "react";
import { getChannels, publishArticle, getArticleById, updateArticleAPI } from "../../apis/article";

const { Option } = Select;
const Publish = () => {
    const [channelsList, setChannelsList] = useState([]);
    const [articleDetail, setArticleDetail] = useState(null); // 用于存储文章详情
    // 回填数据
    const [searchParams] = useSearchParams();
    const id = searchParams.get('id');
    const [form] = Form.useForm();
    const [imageList, setImageList] = useState([]);
    const [imageType, setImageType] = useState(1);

    useEffect(() => {
        const getArticleDetail = async (articleId) => {
            // 调用请求获取文章详情接口
            // 这里假设有一个 getArticleById 接口来获取文章详情
            const res = await getArticleById(articleId);
            console.log('Article Detail:', res);
            form.setFieldsValue({
                title: res.data.data.title,
                channel_id: res.data.data.channel_id,
                content: res.data.data.content,
                type: res.data.data.cover.type,
            });
            // 回填封面类型
            setImageType(res.data.data.cover.type);
            // 显示图片
            setImageList(res.data.data.cover.images.map(url => ({ url })));
            setArticleDetail(res.data.data);
        };

        const fetchChannels = async () => {
            const res = await getChannels();
            console.log('Channels:', res);
            if (res.data && res.data.data && res.data.data.channels) {
                setChannelsList(res.data.data.channels);
            } else {
                console.error('Channels data is not in expected format:', res);
            }
        };
        // 通过路由获取 id
        if (id) {
            getArticleDetail(id);
        }
        fetchChannels();
    }, [id, form]);
    // 发表文章
    const onFinish = async (values) => {
        console.log(values);
        // 校验封面类型imageType是否和实际的图片列表imageList数量是相等的，如果不相等，则提示用户重新选择图片
        if (imageType !== imageList.length) {
            message.error('封面类型和图片数量不一致');
            return;
        }
        const { title, content, channel_id } = values;
        // 准备号提交后端的数据
        const resData = {
            id,
            title,
            content,
            channel_id,
            cover: {
                type: imageType,
                images: imageList.map(item => {
                    if (item.response) {
                        return item.response.data.url;
                    } else {
                        // 编辑时候提交url
                        return item.url;
                    }
                })
            }
        };
        // 处理调用不同的接口 新增 - 新增接口 编辑状态 - 更新接口   id
        if (id) {
            const res = await updateArticleAPI(resData);
            if (res.data.message === 'OK') {
                message.success('修改成功');
            } else {
                message.error('修改失败');
            }
        } else {
            const res = await publishArticle(resData);
            if (res.data.message === 'OK') {
                message.success('发表成功');
            } else {
                message.error('发表失败');
            }
        }
    };
    // onChange上传文件改变时的回调，上传每个阶段都会触发该事件
    const onChange = (info) => {
        if (info.file.status !== 'uploading') {
            console.log(info.file, info.fileList);
        }
        if (info.file.status === 'done') {
            message.success(`${info.file.name}文件上传成功`);
            setImageList(info.fileList);
        } else if (info.file.status === 'error') {
            message.error(`${info.file.name}文件上传失败`);
        }
    };
    // 实现切换封面类型
    const handelChange = (e) => {
        console.log(e.target.value);
        setImageType(e.target.value);
    };
    return (
        <div className="publish">
            <Card
                title={
                    <Breadcrumb
                        items={[
                            { title: <Link to={"/"}>首页</Link> },
                            { title: id ? '编辑文章' : '发表文章' },
                        ]}
                    />
                }
            >
                <Form
                    labelCol={{ span: 4 }}
                    wrapperCol={{ span: 16 }}
                    initialValues={{ type: 1 }}
                    onFinish={onFinish}
                    form={form}
                >
                    <Form.Item
                        label="标题"
                        name="title"
                        rules={[{ required: true, message: "请输入文章标题" }]}
                    >
                        <Input placeholder="请输入文章标题" style={{ width: 400 }} value={articleDetail?.title} />
                    </Form.Item>
                    <Form.Item
                        label="频道"
                        name="channel_id"
                        rules={[{ required: true, message: "请选择文章频道" }]}
                    >
                        <Select placeholder="请选择文章频道" style={{ width: 400 }}>
                            {channelsList.map(item => (
                                <Option key={item.id} value={item.id}>
                                    {item.name}
                                </Option>
                            ))}
                        </Select>
                    </Form.Item>
                    <Form.Item label="封面">
                        <Form.Item name="type">
                            <Radio.Group onChange={handelChange}>
                                <Radio value={1}>单图</Radio>
                                <Radio value={3}>三图</Radio>
                                <Radio value={0}>无图</Radio>
                            </Radio.Group>
                        </Form.Item>
                        {/* listType上传列表的内建样式，支持四种基本样式 text, picture, picture-card 和 picture-circle */}
                        {/* showUploadList是否展示文件列表 */}
                        {/* name发到后台的文件参数名 */}
                        {/* action上传的地址 */}
                        {imageType !== 0 && (
                            <Upload
                                listType="picture-card"
                                showUploadList
                                name="image"
                                action={'http://geek.itheima.net/v1_0/upload'}
                                onChange={onChange}
                                maxCount={imageType}
                                fileList={imageList}
                            >
                                <div style={{ marginTop: 8 }}>
                                    <PlusOutlined />
                                </div>
                            </Upload>
                        )}
                    </Form.Item>
                    <Form.Item
                        label="内容"
                        name="content"
                        rules={[{ required: true, message: "请输入文章内容" }]}
                    >
                        <ReactQuill
                            className="publish-quill"
                            theme="snow"
                            placeholder="请输入文章内容"
                        />
                    </Form.Item>
                    <Form.Item wrapperCol={{ offset: 4 }}>
                        <Space>
                            <Button size="large" type="primary" htmlType="submit">
                                {id ? '更新文章' : '发布文章'}
                            </Button>
                        </Space>
                    </Form.Item>
                </Form>
            </Card>
        </div>
    );
};
export default Publish;